package com.tdj.cdtv.core.service.com.tdj.cdtv.core.dao.com.tdj.cdtv.core.mybaits;

import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;

/**
 * @author: tiandejiang
 * @date: 2018/8/13
 * @version:1.0.0
 */
public final  class RedisCache implements Cache {


    private static final Logger log =
            LoggerFactory.getLogger(RedisCache.class);
    private String id;
    @Resource(name = "redisTemplate")
    private static RedisTemplate<String, Object> redisTemplate;
    private static ValueOperations<String, Object> valueOperations;
    private static int expire;

    public RedisCache(String id) {
        if (id == null) {
            throw new IllegalArgumentException( "Cache Instance ID Could Not Be Null");
        }
        log.info("Create Redis Cache [{}].", id);
        this.id = id;

    }
    @Override
    public String getId() {
        return id;
    }

    @Override
    public void putObject(final Object key,final Object value) {
        log.debug("Put Object Key [{}], Value [{}].", key, value);
        valueOperations.set(prefixedKey(key),
                value, expire, TimeUnit.MILLISECONDS);
    }

    @Override
    public Object getObject(final Object key) {

        Object value = valueOperations.get(prefixedKey(key));
        log.debug("Get Object Key [{}], Value [{}].", key, value);
        return value;
    }

    @Override
    public Object removeObject(final  Object key) {
        log.debug("Remove Object Key [{}].", key);
        redisTemplate.delete(prefixedKey(key));
        return 1;
    }

    @Override
    public void clear() {
        log.debug("Clear Cache Key [{}].", id);
        redisTemplate.delete(redisTemplate.keys(prefixedKey("*")));
    }

    @Override
    public int getSize() {
        log.debug("Get Cache [{}] Size.", id);
        return redisTemplate.keys(prefixedKey("*")).size();
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        return null;
    }

    String prefixedKey(Object key) {
        return prefix() + String.valueOf(key);
    }
    String prefix() {
        return "mybatis_redis_cache:"+id + ":";
    }
    public static void setRedisTemplate(RedisTemplate<String,Object> redisTemplate) {
        RedisCache.redisTemplate = redisTemplate;
        valueOperations = redisTemplate.opsForValue();

    }

    public static void setExpire(int expire) {
        RedisCache.expire=expire;
    }

}
